package cn.niit.smbms.controller.admin;

import cn.niit.smbms.model.reponse.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件上传
 * @author xiaomi
 */

@Slf4j
@Controller
public class FileController {
    /*上传文件的保存目录*/
    private static final String UPLOAD_PATH_FILE = "E:\\upload\files";
    @GetMapping("/upload")
    public String index(){
        return "file";
    }

    @PostMapping("/upload/file")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()){
            log.error("上传的文件为空！");
            return "file";
        }
        /*校验文件的大小*/
        log.info("文件的大小是：{} ", file.getSize());

        /*获取文件名*/
        String fileName = file.getOriginalFilename();
        /*获取文件类型并进行校验*/
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String[] allowedExtension = {"doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "md", "txt"};
        if (!isValidExtension(suffixName, allowedExtension)){
            log.error("文件类型不符合要求：{}", suffixName);
            return "file";
        }
        /*得到本地文件名（保存路径+文件名）*/
        String filePath = UPLOAD_PATH_FILE + fileName;
        /*保存文件*/
        file.transferTo(new File(filePath));
        log.info("文件上传成功，保存为：", fileName, filePath);
        return "file";
    }

    /**
     * 文件的下载
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    @ResponseBody
    @GetMapping("/download/file")
    public BaseResponse<String> downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileName") String fileName){
        /*获取文件的完整路径*/
        String filePath = UPLOAD_PATH_FILE + fileName;
        File file = new File(filePath);
        if (!file.exists()){
            return new BaseResponse<>("10001", "下载失败，文件不存在！");
        }
        try {
            /*响应头的内容类型*/
            ServletContext servletContext = request.getServletContext();
            String mimeType = servletContext.getMimeType(filePath);
            log.info("文件{}---文件的MIME类型是：{}", fileName, mimeType);
            response.setContentType(mimeType);
            //response.addHeader("Content-Dispositoin", "attachment;filenme=" + fileName)   //文件名如果为中文，会出现乱码
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            /*下载文件*/
            FileCopyUtils.copyToByteArray(file);
            log.info("文件下载成功！");
            return new BaseResponse<>("200", "下载成功！");
        }catch (Exception e){
            return new BaseResponse<>("10001", "下载失败:" + e.getMessage());
        }
    }

    /**
     * 文件的上传的下载
     */

    /**
     * 验证上传的文件扩展名是否在允许范围内
     * @param extension
     * @param extensions
     * @return
     */
    private boolean isValidExtension(String extension, String[] extensions){
        for(String allowedExtension : extensions){
            if (extension.equalsIgnoreCase(allowedExtension)){
                return true;
            }
        }
        return false;
    }
}
